﻿using System;
using System.Collections.Generic;
using System.Globalization;
using System.Linq;
using System.Text;

namespace Restful.Net
{
    /// <summary>
    /// Represents the Http Accept Header. 
    /// See http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html
    ///  Accept: text/*;q=0.3, text/html;q=0.7, text/html;level=1,
    ///           text/html;level=2;q=0.4, */*;q=0.5
    /// 
    /// </summary>
    public class Accept
    {

        public Accept(string header, bool fallback = false)
        {
            Fallback = fallback;
            ParseHeader(header);
        }

        public string MediaType
        {
            get;
            set;
        }

        public float Quality
        {
            get;
            set;
        }

        public bool Fallback
        {
            get;
            set;
        }

        /// <summary>
        /// Parses the header into its respective fields.
        /// </summary>
        /// <param name="header">The header.</param>
        private void ParseHeader(string header)
        {
            string[] parts = header.Split(new[] { ';' });

            MediaType = parts[0].Trim();
            Quality = MediaType.IndexOf('*') > -1 ? 0.9999f : 1f;
            if (parts.Length == 1)
            {
                return;
            }

            string q = parts[1];

            string[] qualityParts = q.Split(new[] { '=' });

            if (qualityParts.Length == 1)
            {
                return;
            }

            float quality;
            if (float.TryParse(qualityParts[1], NumberStyles.Float, CultureInfo.InvariantCulture, out quality))
            {
                Quality = quality;
                Quality = MediaType.IndexOf('*') > -1 ? Quality - 0.0001f : Quality;
            }
        }
    }
}
